# 物品数据模拟页面
from flask import jsonify, request
from extensions import db
from sqlalchemy import text
import datetime

# 模拟物品数据
mock_items = [
    {
        'id': 1,
        'name': '笔记本电脑',
        'description': '高性能笔记本电脑，适合编程和设计',
        'price': 899.99,
        'user_id': 1,
        'created_at': datetime.datetime(2023, 1, 15, 10, 30, 0).isoformat(),
        'category': '电子设备',
        'stock': 100,
        'status': '在售'
    },
    {
        'id': 2,
        'name': '智能手机',
        'description': '最新款智能手机，拍照功能强大',
        'price': 5999.99,
        'user_id': 2,
        'created_at': datetime.datetime(2023, 2, 20, 14, 15, 0).isoformat(),
        'category': '电子设备',
        'stock': 150,
        'status': '在售'
    },
    {
        'id': 3,
        'name': '无线耳机',
        'description': '降噪无线耳机，续航长达30小时',
        'price': 1299.00,
        'user_id': 1,
        'created_at': datetime.datetime(2023, 3, 10, 9, 45, 0).isoformat(),
        'category': '电脑配件',
        'stock': 50,
        'status': '在售'
    }
]
def load_item_data():
    """从mock_items读取第一个物品并插入到数据库(SQL语句方式)"""
    # 检查是否已存在相同ID的物品
    check_stmt = text("SELECT id FROM item WHERE id = :id")
    result = db.session.execute(check_stmt, {'id': mock_items[0]['id']}).fetchone()
    if result:
        return {'status': 'error', 'message': 'Item with this ID already exists'}

    # 使用SQL语句插入数据
    insert_stmt = text("""
        INSERT INTO item (
            id, name, description, price, user_id, created_at, 
            category, stock, status
        ) VALUES (
            :id, :name, :description, :price, :user_id, :created_at, 
            :category, :stock, :status
        )
    """)

    try:
        db.session.execute(insert_stmt, {
            'id': mock_items[0]['id'],
            'name': mock_items[0]['name'],
            'description': mock_items[0]['description'],
            'price': mock_items[0]['price'],
            'user_id': mock_items[0]['user_id'],
            'created_at': mock_items[0]['created_at'],
            'category': mock_items[0]['category'],
            'stock': mock_items[0]['stock'],
            'status': mock_items[0]['status']
        })
        db.session.commit()
        return {'status': 'success', 'message': 'Item inserted successfully'}
    except Exception as e:
        db.session.rollback()
        return {'status': 'error', 'message': str(e)}

def unload_item_data():
    """从数据库删除模拟物品数据"""
    try:
        # 使用SQL语句删除数据
        delete_stmt = text("DELETE FROM item WHERE id = :id")
        db.session.execute(delete_stmt, {'id': mock_items[0]['id']})
        db.session.commit()
        return {'status': 'success', 'message': 'Item deleted successfully'}
    except Exception as e:
        db.session.rollback()
        return {'status': 'error', 'message': str(e)}

def register_mock_item_routes(app):
    @app.route('/mock/items', methods=['GET'])
    def get_mock_items():
        # 加载测试数据
        load_item_data()
        
        # 执行查询
        try:
            stmt = text("""SELECT * FROM item""")
            items = db.session.execute(stmt).fetchall()

            result = {  }
            for item in items:
                result = {
                    'id': item.id,
                    'name': item.name,
                    'description': item.description,
                    'price': item.price,
                    'user_id': item.user_id,
                    'created_at': datetime.datetime.fromisoformat(item.created_at).isoformat(),
                    'category': item.category,
                    'stock': item.stock,
                    'status': item.status
                }
            
        except Exception as e:
            result = {'error': str(e)}
        finally:
            # 确保数据被删除
            unload_item_data()

        return jsonify(result), 200